package com.heima.user.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.utils.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;


@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Autowired
    private ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDto dto) {
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        String phone = dto.getPhone();
        String password = dto.getPassword();
        if(StringUtils.isEmpty(phone) && StringUtils.isEmpty(password)){
            //游客登录
            String token = AppJwtUtil.getToken(0L);//获取token
            HashMap<Object, Object> map = new HashMap<>();
            map.put("user",null);
            map.put("token",token);
            return ResponseResult.okResult(map);
        }
        //正常登录
        //构建查询条件
        LambdaQueryWrapper<ApUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApUser::getPhone,phone);
        //从数据库查询用户数据
        ApUser apUser = apUserMapper.selectOne(wrapper);
        //判断用户是否存在
        if(apUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        //获取数据库的盐和密码
        String salt = apUser.getSalt();
        String apUserPassword = apUser.getPassword();
        //将数据库的盐和前端传来的密码加密后与用户数据库存的密码对比
        String md5Password = DigestUtils.md5DigestAsHex((password+salt).getBytes());
        if(!md5Password.equals(apUserPassword)){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        HashMap<String, Object> map = new HashMap<>();
        //生成token
        String token = AppJwtUtil.getToken(apUser.getId().longValue());
        map.put("token",token);
        apUser.setSalt("");
        apUser.setPassword("");
        //构建map存储token和用户信息
        map.put("user",apUser);
        return ResponseResult.okResult(map);
    }
}